package com.nbsaas.boot.controller.web;

import com.nbsaas.boot.rest.response.ListResponse;
import com.nbsaas.boot.rest.response.MapResponse;
import com.nbsaas.boot.rest.response.ResponseObject;
import com.nbsaas.boot.websocket.TalkSocketHandler;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.DefaultSessionKey;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import jakarta.annotation.PreDestroy;
import jakarta.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
public class MessageController {

    @Resource
    private TalkSocketHandler talkSocketHandler;


    @RequestMapping("sendMessage")
    public ResponseObject<?> sendMessage(String client,String message) {
        ResponseObject<?> result=new ResponseObject<>();
        WebSocketSession session = talkSocketHandler.sessionMap.get(client);
        if (session!=null&&session.isOpen()){
            try {
                session.sendMessage(new TextMessage(message));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return result;
    }

    @RequestMapping("list")
    public ListResponse<MapResponse> list() {
      ListResponse<MapResponse> result=new ListResponse<>();
        result.setData(new ArrayList<>());
        List<WebSocketSession> ls = talkSocketHandler.sessions;
        if (ls!=null){
            for (WebSocketSession session : ls) {
                MapResponse mapResponse=new MapResponse();
                mapResponse.put("key",session.getId());
                mapResponse.put("remoteAddress",session.getRemoteAddress());
                mapResponse.put("name",session.getHandshakeHeaders().getFirst("name"));
                result.getData().add(mapResponse);
            }
        }


        return result;
    }

    @RequestMapping("/doTest")
    public ResponseObject<?> doTest(String sessionId) {
        ResponseObject<?> result = new ResponseObject<>();
//        orderInfoApi.listData(Filter.and(Filter.ge("id",1)),Filter.le("id",10),
//                Filter.or(Filter.ge("id",10000)),Filter.le("id",10003)
//                );


        Session session = SecurityUtils.getSecurityManager().getSession(new DefaultSessionKey(sessionId));
        Object principal = session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
        if (principal != null) {
            System.out.println(principal);
        }
        return result;
    }
    @PreDestroy
    public void cleanup() {
        // 清理逻辑
        System.out.println("执行清理");
    }
}
